{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ce5e76a5-222b-408d-b90c-19a801432e66",
   "metadata": {},
   "source": [
    "# LangChain 核心模块 Agent - ReAct\n",
    "\n",
    "ReAct 核心思想是 推理+操作，本示例以` Google Search` 和 `LLM Math` 作为可选操作集合（toolkits），实现 ReAct 功能。\n",
    "\n",
    "以下`SERPAPI_API_KEY`仅为示例，请访问 https://serpapi.com 注册账号并替换为自己的 `API_KEY`（每月100次免费调用）"
   ]
  },
  {
   "cell_type": "code",
   "id": "cd59da96-dda8-42c8-9c82-8460cf3aa75d",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:14:37.389652Z",
     "start_time": "2024-07-13T07:14:37.368940Z"
    }
   },
   "source": [
    "import os\n",
    "\n",
    "# 更换为自己的 Serp API KEY\n",
    "# os.environ[\"SERPAPI_API_KEY\"] = \"1e3c93e0753ac224098370cd71da86150c6609caba6b5aaa307e04b72a5006e1\"\n",
    "os.environ[\"SERPAPI_API_KEY\"] = \"f805ac0b9ece2ec2c2ba22584afed0d6fc881a86cf541c39962ecdb9ea330d25\""
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "cell_type": "code",
   "id": "d03a5086-d453-44f2-898b-0fecb746d0c0",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:15:54.505085Z",
     "start_time": "2024-07-13T07:15:52.643369Z"
    }
   },
   "source": [
    "from langchain_openai import OpenAI\n",
    "\n",
    "llm = OpenAI(temperature=0)"
   ],
   "outputs": [],
   "execution_count": 2
  },
  {
   "cell_type": "code",
   "id": "9e7e7202-625a-4cec-999a-321a40115792",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:16:51.050996Z",
     "start_time": "2024-07-13T07:16:51.036477Z"
    }
   },
   "source": [
    "from langchain.agents import load_tools\n",
    "from langchain.agents import initialize_agent\n",
    "from langchain.agents import AgentType\n",
    "\n",
    "#加载 LangChain 内置的 Tools\n",
    "tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)"
   ],
   "outputs": [],
   "execution_count": 4
  },
  {
   "cell_type": "markdown",
   "id": "d89d569f-5313-42f3-8f1a-ea45fb1ea035",
   "metadata": {},
   "source": [
    "### 使用语言模型（GPT-3）"
   ]
  },
  {
   "cell_type": "code",
   "id": "70af3538-18c4-4c64-99a7-96b32038d31b",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:16:56.472566Z",
     "start_time": "2024-07-13T07:16:56.446159Z"
    }
   },
   "source": [
    "# 实例化 ZERO_SHOT_REACT Agent\n",
    "agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)"
   ],
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "D:\\Dev\\anaconda3\\envs\\langchain\\lib\\site-packages\\langchain_core\\_api\\deprecation.py:119: LangChainDeprecationWarning: The function `initialize_agent` was deprecated in LangChain 0.1.0 and will be removed in 0.3.0. Use Use new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc. instead.\n",
      "  warn_deprecated(\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "cell_type": "code",
   "id": "484bba88-885b-4630-a9a9-b2ff6241df83",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:17:11.554670Z",
     "start_time": "2024-07-13T07:17:01.473640Z"
    }
   },
   "source": [
    "agent.run(\"谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?\")"
   ],
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "D:\\Dev\\anaconda3\\envs\\langchain\\lib\\site-packages\\langchain_core\\_api\\deprecation.py:119: LangChainDeprecationWarning: The method `Chain.run` was deprecated in langchain 0.1.0 and will be removed in 0.3.0. Use invoke instead.\n",
      "  warn_deprecated(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
      "\u001B[32;1m\u001B[1;3m I should use the search engine to find information about Leonardo DiCaprio's girlfriend.\n",
      "Action: Search\n",
      "Action Input: \"Leonardo DiCaprio girlfriend\"\u001B[0m\n",
      "Observation: \u001B[36;1m\u001B[1;3mVittoria Ceretti\u001B[0m\n",
      "Thought:\u001B[32;1m\u001B[1;3m Now I need to use the calculator to calculate 0.43 times the age of Vittoria Ceretti.\n",
      "Action: Calculator\n",
      "Action Input: 0.43 * 23\u001B[0m\n",
      "Observation: \u001B[33;1m\u001B[1;3mAnswer: 9.89\u001B[0m\n",
      "Thought:\u001B[32;1m\u001B[1;3m I now know the final answer.\n",
      "Final Answer: 9.89\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'9.89'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 6
  },
  {
   "cell_type": "markdown",
   "id": "b816038d-6f3a-47cb-b614-e432db8c1883",
   "metadata": {},
   "source": [
    "### 使用聊天模型（GPT-4）"
   ]
  },
  {
   "cell_type": "code",
   "id": "448c877f-577b-4277-a155-51223dc3d949",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:36:04.567976Z",
     "start_time": "2024-07-13T07:35:46.098225Z"
    }
   },
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4-1106-preview\", temperature=0)\n",
    "agent = initialize_agent(tools, chat_model, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n",
    "agent.run(\"谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?两个答案都用中文输出\")"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
      "\u001B[32;1m\u001B[1;3mQuestion: 谁是莱昂纳多·迪卡普里奥的女朋友？\n",
      "Thought: 需要查找莱昂纳多·迪卡普里奥当前的女朋友是谁。\n",
      "Action:\n",
      "```\n",
      "{\"action\": \"Search\", \"action_input\": \"Leonardo DiCaprio current girlfriend 2023\"}\n",
      "```\n",
      "\u001B[0m\n",
      "Observation: \u001B[36;1m\u001B[1;3mVittoria Ceretti\u001B[0m\n",
      "Thought:\u001B[32;1m\u001B[1;3m我现在知道莱昂纳多·迪卡普里奥的女朋友是Vittoria Ceretti。接下来，我需要找出Vittoria Ceretti现在的年龄。\n",
      "\n",
      "Action:\n",
      "```\n",
      "{\"action\": \"Search\", \"action_input\": \"Vittoria Ceretti age\"}\n",
      "```\n",
      "\u001B[0m\n",
      "Observation: \u001B[36;1m\u001B[1;3m26 years\u001B[0m\n",
      "Thought:\u001B[32;1m\u001B[1;3mVittoria Ceretti现在26岁。现在我需要计算26岁的0.43次方。\n",
      "\n",
      "Action:\n",
      "```\n",
      "{\"action\": \"Calculator\", \"action_input\": {\"expression\": \"26^0.43\"}}\n",
      "```\n",
      "\u001B[0m\n",
      "Observation: \u001B[33;1m\u001B[1;3mAnswer: 4.059182145592686\u001B[0m\n",
      "Thought:\u001B[32;1m\u001B[1;3m我现在知道Vittoria Ceretti年龄的0.43次方是大约4.059。现在我可以用中文给出两个答案。\n",
      "\n",
      "Final Answer: 莱昂纳多·迪卡普里奥的女朋友是维多利亚·切雷蒂。她现在年龄的0.43次方是大约4.059。\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'莱昂纳多·迪卡普里奥的女朋友是维多利亚·切雷蒂。她现在年龄的0.43次方是大约4.059。'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 9
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67f4728e-bf1f-4643-a2ee-8f8679ddc58a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
